#pragma once

#include <set>
#include <unordered_map>
#include "template/MinHeap.h"
#include "Event.h"


namespace chaos
{ 
	class TimerQueue
	{
	public:
		static const int INIT_ID_SIZE = 128;
		static const int BYTE2BIT = 8;

		friend EventCentre;
		friend Timer;

		typedef std::unordered_map<int, std::shared_ptr<Timer>> TimerMap;
		typedef std::shared_ptr<Timer> TimerSharedPtr;

		TimerQueue(EventCentre* pCentre);
		~TimerQueue();

		void Launch(EventList& activeEvents);

		//添加定时器,返回定时器ID
		uint32 AddTimer(const EventSharedPtr& timer) { return AddTimer(std::static_pointer_cast<Timer>(timer)); }

		uint32 AddTimer(const TimerSharedPtr& timer);

		uint32 DelTimer(const TimerSharedPtr& timer);

		//获取下一次超时时间
		//-1:当前没有定时器, 0:当前已有就绪的定时器, >0:下个定时器超时时间
		int GetNextTimeout();

		int Size() { return m_timerQueue.Size(); }

		void Clear();

		//分配一个定时器ID, 返回0表示无ID可用
		static timer_id CreateTimerID();

		static void ReleaseTimerID(timer_id id);

	private:
		TimerMap& GetAllTimer() { return m_timerMap; }

		struct TimerCmp
		{
			bool operator()(const TimerSharedPtr& l, const TimerSharedPtr& r) const
			{
				return l->NextRunTime() < r->NextRunTime();
			}
		};

	private:
		MinHeap<TimerSharedPtr, TimerCmp> m_timerQueue;
		EventCentre* m_pCentre;
		TimerMap m_timerMap;
		time_t	m_lastRunTime;

	private:
		static std::vector<byte> s_ids;
		static std::atomic<uint32> s_curTimers;			//定时器个数
		static Mutex s_mutex;
	};

}
